//
//  SNKResetPasswordController.m
//  SleepNews
//
//  Created by Kavee DJ on 2017/1/8.
//  Copyright © 2017年 Kavee DJ. All rights reserved.
//

#import "SNKResetPasswordController.h"
#import <AVOSCloud.h>
#import "UIBarButtonItem+SNK.h"
#import "MBProgressHUD+Extion.h"
#import <SCLAlertView.h>

@interface SNKResetPasswordController ()
@property (weak, nonatomic) IBOutlet UILabel *currentPhoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *pwd1TF;
@property (weak, nonatomic) IBOutlet UITextField *pwd2TF;

@end

@implementation SNKResetPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"密码设置";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem ItemWithTitle:@"完成" target:self action:@selector(accomplish)];
    self.currentPhoneNumber.text = [AVUser currentUser].mobilePhoneNumber;
}

- (void)accomplish {
    IMP_BLOCK_SELF(SNKResetPasswordController)
    // 拦截掉为空的情况
    if ([self.pwd1TF.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入新密码"];
        return;
    }
    
    if ([self.pwd2TF.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请再次输入新密码"];
        return;
    }
    
    // 判断是否一致
    if ([self.pwd1TF.text isEqualToString:self.pwd2TF.text]) {
        // 正则校验
        if ([SNKResetPasswordController validatePassword:self.pwd1TF.text]) {
            [self.view endEditing:YES];
            SCLAlertView *alert = [[SCLAlertView alloc] init];
            [alert addButton:@"确定" actionBlock:^(void) {
                // 更新云端
                [AVUser currentUser].password = block_self.pwd1TF.text;
                [[AVUser currentUser] saveInBackground];
                
                [MBProgressHUD showSuccess:@"成功修改密码"];
                [block_self.navigationController popViewControllerAnimated:YES];
            }];
            [alert showWarning:self title:@"确定要修改密码吗?" subTitle:nil closeButtonTitle:@"取消" duration:0.0f];
        } else {
            [MBProgressHUD showSuccess:@"密码不合法"];
        }
    } else {
        [MBProgressHUD showError:@"两次输入的密码不一致"];
    }
    
}

//密码正则
+ (BOOL)validatePassword:(NSString*)passWord

{
    
    NSString*passWordRegex =@"^[a-zA-Z0-9]{6,20}+$";
    
    NSPredicate*passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    
    return[passWordPredicate  evaluateWithObject:passWord];
    
}

@end
